var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var Base = require('../base.js');
var app = getApp();

var CutList = function({
  page,
  scope,
  cmpt
}) {
  Base.apply(this, arguments);

  this._timerList = {};
  this._timerId = null;
  this.init();
}

common.extend(CutList, Base);

Object.assign(CutList.prototype, {
  init() {
    var _self = this;
    var cmpt = this.curCmpt;

    ajax.G('/openapi/CActivity/haggleActList', {}, function(res) {
      var list = res.result || [];

      list.forEach(function(item, index) {
        var leftTime = item.left_time;

        if (leftTime && leftTime > 0) {
          _self._timerList[index] = leftTime;
        }
      });
      _self.setData({
        list,
        timerStrs: {}
      });

      if (_self._timerId) {
        clearTimeout(_self._timerId);
      }
      _self._timerDown();

    });
  },

  _timerDown() {
    var _self = this;
    var timerStrs = _self.getData('timerStrs');
    var _timerList = _self._timerList;
    var isOver = false;
    var _timerListKeys = Object.keys(_timerList);

    if (_timerListKeys.length == 0) {
      return;
    }
    _timerListKeys.some(function(key) {
      var sec = _timerList[key];

      timerStrs[key] = util.getTimeBySec(sec, 'd');

      if (sec == 0) {
        isOver = true;
        return true;
      }
      _timerList[key] = --sec;
    });

    if (isOver) {
      _self.init();
      clearTimeout(self._timerId);
      return;
    }
    _self.setData({
      timerStrs,
    });
    _self._timerId = setTimeout(() => {
      _self._timerDown();
    }, 1000);
  },

});

CutList.props = {
  name: 'cutList'
};

module.exports = CutList;